package com.audaque.springboot.foshanupload.gateway.filter;

/**
 * @author zgb
 * @desc ...
 * @date 2023-08-01 17:25:24
 */

import com.audaque.springboot.foshanupload.authcore.constants.AuthConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 存放sessionId到请求头
 */
@Slf4j
@Component
public class SessionIdHeaderFilter implements GlobalFilter, Ordered {



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.debug("执行前置过滤器逻辑");
        AtomicReference<String> sessionIdAtom=new AtomicReference<>();
        exchange.getSession().subscribe(e->{
            sessionIdAtom.set(e.getId());
        });
        String sessionId = sessionIdAtom.get();
        if(StringUtils.isNotBlank(sessionId)){
            byte[] b = Base64Utils.encode(sessionId.getBytes());
            String[] headerValues = {new String(b)};
            ServerHttpRequest build = exchange.getRequest()
                    .mutate()
                    //设置header
                    .header(AuthConst.MY_SESSIONID_KEY, headerValues)
                    .build();
            //更新header
            ServerWebExchange newExchange = exchange.mutate().request(build).build();
            return chain.filter(newExchange);
        }
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            log.debug("执行后置过滤器逻辑");

        }));

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
